重定向
重定向
可以使用redirect助手函数进行重定向
phpnamespace app\index\controller;class Index{public function hello(){return redirect('http://www.thinkphp.cn');}}
redirect函数和控制器的redirect方法的参数顺序有所区别
重定向传参
如果是站内重定向的话,可以支持URL组装,有两种方式组装URL,第一种是直接使用完整地址(/打头)
redirect('/index/index/hello/name/thinkphp');
这种方式会保持原来地址不做任何转换,第二种方式是使用params方法配合,例如:
redirect('hello')->params(['name'=>'thinkphp']);
最终重定向的URL地址和前面的一样的,系统内部会自动判断并调用url(用于快速生成URL地址的助手函数)方法进行地址生成,或者使用下面的方法
redirect('hello',['name'=>'thinkphp']);
还可以支持使用with方法附加Session闪存数据重定向。
phpnamespace app\index\controller;class Index{public function index(){return redirect('hello')->with('name','thinkphp');}public function hello(){$name = session('name');return 'hello,'.$name.'!';}}
从示例可以看到重定向隐式传值使用的是Session闪存数据隐式传值,并且仅在下一次请求有效,再次访问重定向地址的时候无效。
记住请求地址
在很多时候,我们重定向的时候需要记住当前请求地址(为了便于跳转回来),我们可以使用remember方法记住重定向之前的请求地址。
下面是一个示例,我们第一次访问index操作的时候会重定向到hello操作并记住当前请求地址,然后操作完成后到restore方法,restore方法则会自动重定向到之前记住的请求地址,完成一次重定向的回归,回到原点!(再次刷新页面又可以继续执行)
phpnamespace app\index\controller;class Index{public function index(){// 判断session完成标记是否存在if (session('?complete')) {// 删除sessionsession('complete', null);return '重定向完成,回到原点!';} else {// 记住当前地址并重定向return redirect('hello')->with('name', 'thinkphp')->remember();}}public function hello(){$name = session('name');return 'hello,' . $name . '!
点击回到来源地址';}public function restore(){// 设置session标记完成session('complete', true);// 跳回之前的来源地址return redirect()->restore();}}